const http = require("http");
const path = require("path");
const fs = require("fs");
var dirPath = path.join(__dirname, "/upload");

var img = [];

function parseHead(str) {
    var arr = str.split("\r\n");
    var fileArr = arr[1];
    var strk = fileArr.split(";");
    var name = strk[2].split("=")[1];
    var imgarr = arr.slice(4, arr.length - 2);
    var imgStr = imgarr.join("\r\n");
    var buf = Buffer.from(imgStr, "binary");
    fs.writeFileSync(path.join(dirPath, name.slice(1, -1)), buf, {
        encoding: "binary",
    });
}

http.createServer((req, res) => {
    var urlObj = new URL(req.url, "http://localhost:8080/");
    var pathname = urlObj.pathname;
    if (pathname == "/") {
        var fileContent = fs.readFileSync("./index.html");
        res.writeHead(200, { "Content-Type": "text/html;charset=utf-8" });
        res.write(fileContent);
        res.end();
    } else if (pathname == "/upload") {
        var str = "";
        req.setEncoding("binary");
        req.on("data", (chunk) => {
            str += chunk;
        });
        req.on("end", () => {
            parseHead(str);
        });
        res.end("success");
    } else if (pathname == "/list") {
        var fileContent = fs.readFileSync("./list.html");
        res.writeHead(200, { "Content-Type": "text/html;charset=utf-8" });
        res.write(fileContent);
        res.end();
    } else if (pathname == "/getlist") {
        var file = fs.readdirSync(dirPath);
        for (var i = 0; i < file.length; i++) {
            img[i] = file[i];
        }
        var imgArray = JSON.stringify(img);
        res.writeHead(200, { "Content-Type": "text/plain" });
        res.write(imgArray);
        res.end();
    } 
    else if (pathname.indexOf("upload/") >= 0) {
        var filePath = path.join(__dirname, "/"+pathname);
        var fileContent = fs.readFileSync(filePath);
        res.writeHead(200, { "Content-Type": "image/*;charset=utf-8" });
        res.write(fileContent);
        res.end();
    }
}).listen(8080);
console.log("server is listening on port 8080");
